package com.conferences.web;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.conferences.model.Conference;
import com.conferences.model.ConferenceStatus;
import com.conferences.web.model.Mailer;

@Controller
@RequestMapping(value = "/conference")
public class ConferenceController extends App {

	@RequestMapping(value = "/add.htm", method = RequestMethod.GET)
	public String add(ModelMap model) {
		Conference c = new Conference();
		model.addAttribute("CONFERENCE", c);
		return "conference_add";
	}

	@RequestMapping(value = "/edit/{conferenceId}.htm", method = RequestMethod.GET)
	public String edit(@PathVariable String conferenceId, ModelMap model) {
		Conference c = conferenceService.get(Long.valueOf(conferenceId));
		model.addAttribute("CONFERENCE", c);
		return "conference_edit";
	}

	@RequestMapping(value = "/delete/{conferenceId}.htm", method = RequestMethod.GET)
	public String delete(@PathVariable String conferenceId, ModelMap model) {
		Conference c = conferenceService.get(Long.valueOf(conferenceId));
		conferenceService.delete(c);
		return "redirect:/conference/list/user.htm";
	}

	@RequestMapping(value = "/leave/{conferenceId}.htm", method = RequestMethod.GET)
	public String leave(@PathVariable String conferenceId, ModelMap model) {
		Conference c = conferenceService.get(Long.valueOf(conferenceId));

		User loggedUser = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

		List<com.conferences.model.User> newParticipantList = new ArrayList<com.conferences.model.User>();
		for (com.conferences.model.User user : c.getUsers()) {
			if (user.getUsername().compareTo(loggedUser.getUsername()) != 0) {
				newParticipantList.add(user);
			}
		}

		c.setUsers(newParticipantList);
		conferenceService.save(c);

		return "redirect:/conference/list/user.htm";
	}

	@RequestMapping(value = "/join/{conferenceId}.htm", method = RequestMethod.GET)
	public String join(@PathVariable String conferenceId, ModelMap model) {
		Conference c = conferenceService.get(Long.valueOf(conferenceId));

		User loggedUser = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		List<com.conferences.model.User> newParticipantList = c.getUsers();
		newParticipantList.add(userService.findByUsername(loggedUser.getUsername()));

		c.setUsers(newParticipantList);

		conferenceService.save(c);

		return "redirect:/conference/list/user.htm";
	}

	@RequestMapping(value = "/save.htm", method = RequestMethod.POST)
	public String processForm(@ModelAttribute(value = "CONFERENCE") Conference conference, BindingResult result) {
		if (result.hasErrors()) {
			return "redirect:/conference/list/user.htm";
		}

		ConferenceStatus status = new ConferenceStatus();
		status.setStatus("Robocza");
		status.setId(1);
		conference.setStatus(status);

		User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		conference.setAuthor(userService.findByUsername(user.getUsername()));

		conferenceService.save(conference);
		return "redirect:/conference/list/user.htm";
	}

	@RequestMapping(value = "/view/{conferenceId}.htm", method = RequestMethod.GET)
	public String view(@PathVariable(value = "conferenceId") String conferenceId, Model model) {
		Long itemId = Long.valueOf(conferenceId);
		Conference conference = conferenceService.get(itemId);

		User user = (org.springframework.security.core.userdetails.User) SecurityContextHolder.getContext().getAuthentication()
				.getPrincipal();
		com.conferences.model.User userObj = userService.findByUsername(user.getUsername());
		com.conferences.model.User userObject = userService.get(userObj.getId());

		model.addAttribute("loggedUser", userObject);
		model.addAttribute("conference", conference);
		return "conference_view";
	}

	@RequestMapping(value = "/remind/{conferenceId}.htm", method = RequestMethod.GET)
	public String remind(@PathVariable(value = "conferenceId") String conferenceId, Model model) {
		Long itemId = Long.valueOf(conferenceId);
		Conference conference = conferenceService.get(itemId);

		User user = (org.springframework.security.core.userdetails.User) SecurityContextHolder.getContext().getAuthentication()
				.getPrincipal();
		com.conferences.model.User userObj = userService.findByUsername(user.getUsername());
		com.conferences.model.User userObject = userService.get(userObj.getId());
		new Mailer().sendEmail(conference, conference.getUsers());
		return "redirect:/conference/list/user.htm";
	}

	@RequestMapping(value = "/printlist/{conferenceId}.htm", method = RequestMethod.GET)
	@ResponseBody
	public String printList(@PathVariable(value = "conferenceId") String conferenceId, Model model) {
		Long itemId = Long.valueOf(conferenceId);
		Conference conference = conferenceService.get(itemId);

		List<com.conferences.model.User> users = conference.getUsers();
		StringBuilder response = new StringBuilder();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

		response.append("<html><head><meta charset=\"utf-8\" /></head><body>");
		response.append("<h2>Temat: " + conference.getSubject() + "</h2>");
		response.append("<p>Data: " + dateFormat.format(conference.getDate()) + "</p>");
		response.append("<br/><p Uczestnicy: </p>");

		int i = 0;
		for (com.conferences.model.User user : users) {
			response.append(i).append(" ");
			response.append(user.getFirstname() + " " + user.getLastname() + " ");
			response.append(user.getEmail());
			response.append("<br/>");
			i++;
		}
		response.append("</body></html>");
		return response.toString();
	}

	@RequestMapping(value = "/list/user.htm", method = RequestMethod.GET)
	public String listUser(ModelMap model) {
		User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		com.conferences.model.User userObj = userService.findByUsername(user.getUsername());
		com.conferences.model.User userObject = userService.get(userObj.getId());

		List<Conference> asParticipantList = userObject.getConferences();
		List<Conference> conferences = conferenceService.list(userObject);

		model.addAttribute("conferencesAsParticipant", asParticipantList);
		model.addAttribute("conferences", conferences);

		return "user_conference";
	}

	@InitBinder
	public void initBinder(WebDataBinder webDataBinder) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		dateFormat.setLenient(false);
		webDataBinder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
	}
}
